package com.woniuxy.course.controller;

import com.woniuxy.commons.entity.Courseware;
import com.woniuxy.commons.entity.ResponseEntity;
import com.woniuxy.commons.utils.CodeUtils;
import com.woniuxy.course.utils.StatusCode;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 王光强
 * @date 2020/7/17 0017-11:32
 */
@RestController
@RequestMapping("/upload")
public class TestUploadFileController {

    @RequestMapping(value = "/UploadAction", method = RequestMethod.POST, consumes = "multipart/*")
    @ResponseBody
    public Map UploadAction(@RequestParam("file") MultipartFile file, Model model, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        //获取文件字节数组
        byte [] bytes = file.getBytes();
        long fileSize =file.getSize();
        System.out.println("文件大小：" + fileSize + "B");
        System.out.println(fileName);
        if (fileName.indexOf("\\") != -1) {
            fileName = fileName.substring(fileName.lastIndexOf("\\"));
        }
        // 获取项目名称,文件上传位置
        String path = ResourceUtils.getURL("classpath:").getPath();// 当前项目的根路径
        System.out.println(path);
        File root = new File(path);
        path =root.getParent();
         root = new File(path);
        File main= root.getParentFile();
        File fileDir = new File(main, "/src/main/resources/static/updatefile/file");
        System.out.println(fileDir);
        File f = new File(fileDir.getPath(),fileName);
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        try{
            //写入指定文件夹
            OutputStream out = new FileOutputStream(f);
            out.write(bytes);
            out.flush();//清空缓冲区的数据流
            out.close();//关闭流
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        return map;
    }

    @RequestMapping("/addCourseware")
    @ResponseBody
    public Map addCourseware(Courseware courseware){
        System.out.println(courseware.toString());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        return map;
    }

    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST,consumes = "multipart/*")
    @ResponseBody
    public Map UploadAction(@RequestParam("upload") MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        //获取文件字节数组
        byte [] bytes = file.getBytes();
        long fileSize =file.getSize();
        System.out.println("文件大小：" + fileSize + "B");
        System.out.println(fileName);
        if (fileName.indexOf("\\") != -1) {
            fileName = fileName.substring(fileName.lastIndexOf("\\"));
        }
        // 获取项目名称,文件上传位置
        String path = ResourceUtils.getURL("classpath:").getPath();// 当前项目的根路径
        System.out.println(path);
        File root = new File(path);
        path =root.getParent();
        root = new File(path);
        File main= root.getParentFile();
        File fileDir = new File(main, "/src/main/resources/static/updatefile/images");
        System.out.println(fileDir);
        File f = new File(fileDir.getPath(),fileName);
        if(!fileDir.exists()){
            fileDir.mkdir();
        }
        try{
            //写入指定文件夹
            OutputStream out = new FileOutputStream(f);
            out.write(bytes);
            out.flush();//清空缓冲区的数据流
            out.close();//关闭流
        }catch (Exception e){
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        return map;
    }


    /**
     * 通过文件路径直接修改文件名
     *
     * @param filePath    需要修改的文件的完整路径
     * @param newFileName 需要修改的文件的名称
     * @return
     */
    private String FixFileName(String filePath,String oldName, String newFileName) {
        File f = new File(filePath, oldName);
        System.out.println(f);
        if (!f.exists()) { // 判断原文件是否存在（防止文件名冲突）
            return null;
        }
        String fileName=f.getName();
        String fileTyle=fileName.substring(fileName.lastIndexOf("."),fileName.length());
        System.out.println(fileTyle);

        try {
            if(fileName.indexOf(".")>=0) {
                fileName = fileName.substring(0,fileName.lastIndexOf("."));
                System.out.println(fileName);
            }
            f.renameTo(new File(filePath,newFileName+fileTyle)); //改名
            System.out.println(f);
        } catch (Exception err) {
            err.printStackTrace();
            return null;
        }
        return "success";
    }

    @RequestMapping("/rename")
    public ResponseEntity<Void> rename(String newFileName,String oldName) throws FileNotFoundException {
        ResponseEntity<Void> voidResponseEntity = new ResponseEntity<>();
        // 获取项目名称,文件上传位置
        String path = ResourceUtils.getURL("classpath:").getPath();// 当前项目的根路径
        System.out.println(path);
        File root = new File(path);
        path =root.getParent();
        File main= root.getParentFile();
        path =main.getParent();
        System.out.println(path);
        path= path+"/src/main/resources/static/updatefile/file";
        System.out.println(path);
        try {
            String meg =FixFileName(path,oldName,newFileName);
            return voidResponseEntity.setCode(CodeUtils.SUCCESS_CODE).setMessage("修改成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return voidResponseEntity.setCode(StatusCode.SERVER_ERROR).setMessage("系统异常");
    }
}